package Homework.dayH;

import com.sun.xml.internal.ws.handler.ClientLogicalHandlerTube;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.spec.RSAOtherPrimeInfo;
import java.util.ArrayList;
import java.util.List;

public class Server {
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server() {
        try {
            System.out.println("正在启动服务端......");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接......");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;
        private String nickname;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                nickname = br.readLine();

                String message;

                while ((message = br.readLine())!= null){
                    System.out.println(nickname + "[" + host + "]说:" + message);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}


/*
 *thred  线程
 * start 开始
 * run 运行
 * sleep 休眠
 * wait 等待
 * notify 通知
 * Memory 内次
 * stack 堆栈
 * Runnable 可运行的
 * serializable 串行化
 * synchronized 同步
 */









